package com.msh.frame.common.util;

import com.msh.frame.client.define.StringDef;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class URLCoderUtil {

  public static String encode(String param) {
    try {
      param = URLEncoder.encode(param, "utf-8");
    } catch (UnsupportedEncodingException e) {
    }
    return param;
  }

  public static String decode(String param) {
    try {
      param = URLDecoder.decode(param, "utf-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return param;
  }

  public static String buildQuery(MultiValueMap<String, String> params) {
    if (CollectionUtils.isEmpty(params)) {
      return StringDef.EMPTY;
    }
    StringBuilder queryBuilder = new StringBuilder();
    params.forEach((name, values) -> {
      if (CollectionUtils.isEmpty(values)) {
        if (queryBuilder.length() != 0) {
          queryBuilder.append('&');
        }

        queryBuilder.append(name);
      } else {

        for (String value : values) {
          if (queryBuilder.length() != 0) {
            queryBuilder.append('&');
          }

          queryBuilder.append(name);
          if (value != null) {
            queryBuilder.append('=').append(value);
          }
        }
      }

    });
    return queryBuilder.toString();
  }
}
